package com.chinaoryx.er;

import java.sql.*;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: hyman.zhang
 * Date: 12-1-31
 * Time:
 */
public class DataTransfer {

    /**
     *
     * @param frmConn
     * @param toConn
     * @param entity
     */
    public void transfer(Connection frmConn, Connection toConn, EntityDefination entity) throws SQLException {

        // get the pri table list
        String sql = entity.getSqlForList();
        List<Map> list = new ArrayList<Map>();
        Statement stmt = null;
        ResultSet rs = null;
        
        stmt = frmConn.createStatement();
        rs = stmt.executeQuery(sql);
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();

        while (rs.next()) {
            Map<String, Object> result = new HashMap<String, Object>();

            for (int i = 0; i<count; i++) {
                String columnLabel = rsmd.getColumnLabel(i+1);
                Object val = rs.getObject(i+1) ;
                result.put(columnLabel, val);
                
            }
            list.add(result);
        }
        rs.close();
        stmt.close();


        moveEntityList(frmConn, toConn, entity, list);
        
    }

    public void moveEntityList(Connection frmConn, Connection toConn, EntityDefination entity, List<Map> list) throws SQLException {
        if (list == null) {
            return;
        }
        int recordCount = 1;
        toConn.setAutoCommit(false);
        Map<String, PreparedStatement> pstmtMap = new LinkedHashMap<String, PreparedStatement>();
        for(Map result: list) {
            entity.getTable().moveTableRecord(frmConn,toConn, result, pstmtMap);
//            pstmtMap.

            System.out.println(recordCount++);
//            this.saveTable(frmConn,toConn, entity.getTable(), result);
        }

        for (Map.Entry<String, PreparedStatement> entry : pstmtMap.entrySet()) {
            entry.getValue().executeBatch();
            entry.getValue().close();
        }
        toConn.commit();
    }




}
